var game = {
	$bullet: null,
	$fly:    null,
	count:   0,
	running: false
};

game.init = function() {
	game.$bullet = $('.bullet');
	game.$fly    = $('.fly');
	game.watching();

	game.start();

	// 点击－发射炮弹事件
	$(document).on('click', function() {
		if(game.running) {
			game.$bullet.css('bottom', 66).stop(true).animate({bottom: 400});
		}else {
			game.start();
		}
	});
};

game.start = function() {
	game.count = 0;
	game.renderCount();
	game.running = true;
	game.runFly();
};

game.stop = function() {
	game.$fly.stop(true);
	game.$bullet.stop(true);
	game.running = false;
};

game.runFly = function() {
	game.$fly.css('left', -100).stop(true).animate({left: 800}, 800 * (1.5 + Math.random()), 'linear', function() {
		game.runFly();
	});
}

game.renderCount = function() {
	$('#count').text(game.count);
};

game.watching = function() {
	window.setInterval(function() {
		if(!game.running) return;

		var flyPos    = game.$fly.position();
		var bulletPos = game.$bullet.position();
		if(flyPos.left>700) {
			return game.stop();
		}

		if(bulletPos.top>-20 && bulletPos.top<100 && (bulletPos.left-flyPos.left)>-20 && (bulletPos.left-flyPos.left<100)) {
			game.$fly.stop(true, true);

			game.count ++;
			game.renderCount();
		}
	}, 1000/50);
};

$(game.init);